import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/main/mine/block_list/mine_block_list_logic.dart';
import 'package:ride_rex/net/common_global_url.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/sqlite/db_manager.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../main/discover/discover_bean.dart';
import '../service/log_service.dart';

class ApiPersonDetail extends CommonApi {
  ApiPersonDetail._({
    required String userId,
    required String complainCategory,
    String? complainSub,
  }) : super(
          CommonGlobalUrl.addToBlockList,
          params: {
            'broadcasterId': userId,
            'complainCategory': complainCategory,
            if (complainSub.notEmpty) 'complainSub': complainSub,
          },
        );

  ///举报
  ApiPersonDetail.report({required String userId, required String complainSub})
      : this._(userId: userId, complainCategory: 'Report', complainSub: complainSub);

  ///拉黑
  ApiPersonDetail.block({required String userId}) : this._(userId: userId, complainCategory: 'Block');

  ///关注
  ApiPersonDetail.follow({required String followUserId})
      : super(CommonGlobalUrl.addFriend, params: {'followUserId': followUserId});

  ///取消关注
  ApiPersonDetail.unfollow({required String followUserId})
      : super(CommonGlobalUrl.unfriend, params: {'followUserId': followUserId});

  ///关注列表
  ApiPersonDetail.followList() : super(CommonGlobalUrl.getFriendsList);
}

///
class CommonLogic {
  static const String keyListenerBlock = "key_listener_block";
  static const String keyListenerFollow = "key_listener_follow";
  static const String keyListenerUnfollow = "key_listener_unfollow";
  static const String keyListenerUnblock = "key_listener_unblock";
  static const String keyListenerArticleLike = "key_listener_article_like";
  static const String keyListenerArticleCancelLike = "key_listener_article_cancel_like";

  ///拉黑
  static Future block(String userId) async {
    DbManager.blockUser(userId: userId, isBlock: '1');
    await ApiPersonDetail.block(userId: userId).post();
    CommonObservable().publishChange(keyListenerBlock, userId);
  }

  ///取消拉黑
  static Future unblock(String userId) async {
    DbManager.blockUser(userId: userId, isBlock: '0');
    await ApiMineBlockList.unblock(userId: userId).post();
    CommonObservable().publishChange(keyListenerUnblock, userId);
  }

  ///关注
  static Future follow(String userId) async {
    DbManager.followUser(userId: userId, isFollow: '1');
    await ApiPersonDetail.follow(followUserId: userId).post();
    CommonObservable().publishChange(keyListenerFollow, userId);
  }

  ///取消关注
  static Future unfollow(String userId) async {
    DbManager.followUser(userId: userId, isFollow: '0');
    await ApiPersonDetail.unfollow(followUserId: userId).post();
    CommonObservable().publishChange(keyListenerUnfollow, userId);
  }

  ///点赞
  static Future like({required String recordId}) async {
    DbManager.like(recordId: recordId);
    CommonObservable().publishChange(keyListenerArticleLike, recordId);
  }

  ///取消点赞
  static Future cancelLike({required String recordId}) async {
    DbManager.cancelLike(recordId: recordId);
    CommonObservable().publishChange(keyListenerArticleCancelLike, recordId);
  }

  static void onTapMore(String userId, {bool showFollow = true}) {
    var config = ActionSheetConfig(
        text: 'Follow',
        onTap: () async {
          if (Loading.predicate(() => userId.empty, 'user_id required')) return;
          Loading.show();
          await CommonLogic.follow(userId);
          Loading.toast('Follow success', closeLoading: true);
        });
    if (!showFollow) {
      config = ActionSheetConfig(
          text: 'Unfollow',
          onTap: () async {
            if (Loading.predicate(() => userId.empty, 'user_id required')) return;
            Loading.show();
            await CommonLogic.unfollow(userId);
            Loading.toast('Unfollow success', closeLoading: true);
          });
    }
    PersonDetailActionSheet.actionSheet(items: [
      config,
      ActionSheetConfig(
          text: 'Block',
          onTap: () async {
            LMLogManager.stat(page: 'block');
            if (Loading.predicate(() => userId.empty, 'user_id required')) return;
            Loading.show();
            await CommonLogic.block(userId);
            await CommonLogic.unfollow(userId);
            CommonRoute.close();
            Loading.toast('Block success', closeLoading: true);
          }),
      ActionSheetConfig(text: 'Report', onTap: () => onTapReport(userId)),
    ]);
  }

  static void onTapReport(String userId) {
    if (Loading.predicate(() => userId.empty, 'user_id required')) return;
    PersonDetailActionSheet.actionSheet(items: [
      ActionSheetConfig(text: 'Pornographic', onTap: () => _report('Pornographic', userId)),
      ActionSheetConfig(text: 'False gender', onTap: () => _report('False gender', userId)),
      ActionSheetConfig(text: 'Fraud', onTap: () => _report('Fraud', userId)),
      ActionSheetConfig(text: 'Political sensitive', onTap: () => _report('Political sensitive', userId)),
      ActionSheetConfig(text: 'Other', onTap: () => _report('Other', userId)),
    ]);
  }

  static void _report(String complainSub, String userId) async {
    LMLogManager.stat(page: 'report');
    Loading.show();
    await ApiPersonDetail.report(userId: userId, complainSub: complainSub).post();
    Loading.toast('Report success', closeLoading: true);
  }
}

class PersonDetailLogic extends GetxController with GetSingleTickerProviderStateMixin {
  PersonDetailLogic(this.bean);

  final FeedUserBean bean;

  final List<String> titles = ['Post', 'Medal'];
  final List<String> icons = [Assets.pngPersonDetailPost, Assets.pngPersonDetailMedal];
  late final TabController tabController = TabController(length: titles.length, vsync: this)
    ..addListener(() {
      selectIndex = tabController.index;
      update();
    });

  final ValueNotifier<double> appBarOpacityNotifier = ValueNotifier<double>(0);

  late final ScrollController scrollController = ScrollController()
    ..addListener(() {
      double alpha = scrollController.offset / 170.w;

      if (alpha < 0) {
        alpha = 0;
      } else if (alpha > 1) {
        alpha = 1;
      }

      appBarOpacityNotifier.value = alpha;
    });

  @override
  void onReady() async {
    super.onReady();
    CommonObservable().addObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().addObserver(CommonLogic.keyListenerUnfollow, unfollow);
  }

  @override
  void onClose() {
    super.onClose();
    CommonObservable().removeObserver(CommonLogic.keyListenerFollow, follow);
    CommonObservable().removeObserver(CommonLogic.keyListenerUnfollow, unfollow);
  }

  void follow(key, [value]) {
    String userId = value ?? '';
    if (userId.equals(bean.userId)) {
      bean.isFriend = true;
      update();
    }
  }

  void unfollow(key, [value]) {
    String userId = value ?? '';
    if (userId.equals(bean.userId)) {
      bean.isFriend = false;
      update();
    }
  }

  int selectIndex = 0;

  void changeIndex(int index) {
    selectIndex = index;
    tabController.animateTo(index);
    update();
  }
}

class PersonDetailActionSheet {
  static void actionSheet({
    /// items
    required List<ActionSheetConfig> items,
  }) {
    List<Widget> children = items.map((e) {
      return Column(
        children: [
          ButtonWidget.text(
            e.text,
            alignment: Alignment.center,
            height: 56.w,
            fontSize: 16,
            textColor: '#142220'.toColor,
            onTap: () {
              Get.back();
              e.onTap.call();
            },
            hasInkWell: false,
          ),
          CommonDivider(height: 0.5.w, color: const Color(0xFFEDEDED)),
        ],
      );
    }).toList();

    Widget cancel = Container(
      padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight, top: 30.w),
      alignment: Alignment.center,
      child: ButtonWidget.text(
        'Cancel',
        alignment: Alignment.center,
        height: 44.w,
        width: 183.w,
        fontSize: 16,
        textColor: Colors.white,
        fontWeight: FontWeight.bold,
        onTap: Get.back,
        gradient: AppColors.primaryGradient,
        hasInkWell: false,
        borderRadius: 44.w,
      ),
    );

    // 调用 标准模式框
    ActionBottomSheet.normal(
      context: Get.context!,
      contentPadding: const EdgeInsets.all(0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [...children, cancel],
      ),
    );
  }
}
